package utils;

import database.DatabaseBasic;
import database.UserDb;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;

/**
 * Created by jimmyhsu on 2016/12/9.
 */
public class QrCodeUtil {
    public static String createPassword(int length) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789(){}<>~=,.;:";
        StringBuffer sb = new StringBuffer();
        int maxLength = chars.length();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(maxLength - 1)));
        }
        return sb.toString();
    }

    public static boolean signIn(String qrcode, String studentId, String password) {
        String sql = "select * from qrcode where qrcode=\'" + qrcode + "\'";
        DatabaseBasic sqlHelper = new DatabaseBasic();
        ResultSet resultSet = sqlHelper.executeSql(sql);
        try {
            if (resultSet.next()) {
                //还没有过期
                if (resultSet.getLong("createTime")
                        + resultSet.getInt("expiresIn") >= System.currentTimeMillis()) {

                    int courseId = resultSet.getInt("courseId");
                    resultSet.close();
                    sql = "select * from takecourse where studentId=\'" +
                            studentId + "\' and courseId=" + courseId;
                    ResultSet resultSet1 = sqlHelper.executeSql(sql);
                    if (resultSet1.next()) {
                        resultSet1.close();
                        sql = "update takecourse set attendance=\'出席\' where studentId=\'" +
                                studentId + "\' and courseId=" + courseId;
                        sqlHelper.executeSqlUpdate(sql);
                        sqlHelper.recycle();
                        return true;
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
